<template>
  <j-modal
    :title="editId ? '编辑映射' : '新增映射'"
    :width="1200"
    :visible.sync="modalVisible"
    :maskClosable="false"
    switchFullscreen
  >
    <a-spin :spinning="submitLoading">
      <a-form-model ref="form" :model="formData" :rules="rules">
        <a-divider orientation="left"> 平台信息 </a-divider>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="平台SKU" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="platformSkuCode">
              <a-input
                v-model="formData.platformSkuCode"
                placeholder="请输入完整的平台SKU编码"
                :maxLength="50"
              ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="店铺名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="shopId">
              <j-url-select
                placeholder="请选择平台SKU对应的店铺名称"
                v-model="formData.shopId"
                optionLabel="storeName"
                url="/hzkj-oms/oms/store/storeAuthAmazon/storeList"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-divider orientation="left"> 包含产品 </a-divider>
        <div style="margin-bottom: 10px">
          <a-button type="primary" icon="plus" @click="showProductCheck = true" style="margin-right: 10px"
            >添加SKU</a-button
          >
          <a-button v-show="selectedRowKeys.length" type="danger" ghost @click="delProduct()">批量删除</a-button>
        </div>
        <a-table
          bordered
          :pagination="false"
          :columns="formColumns"
          :data-source="formData.hzArchiveShopSkuItemsList"
          :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          rowKey="skuCode"
        >
          <template #imgSlot="text, record">
            <viewer :images="[record.imgUrl]" class="img-box">
              <img :src="record.imgUrl" />
              <div class="hint-text">{{ record.imgUrl ? '点击看大图' : '暂无图片' }}</div>
            </viewer>
          </template>
          <template #numTitle> <span class="required-ico">*</span>产品数量 </template>
          <template #numSlot="text, record, index">
            <a-form-model-item
              :prop="'hzArchiveShopSkuItemsList.' + index + '.count'"
              :rules="{
                required: true,
                message: '数量不能为空',
                trigger: 'blur',
              }"
            >
              <a-input-number v-model="record.count" :min="1" :max="99999999" :step="1" :precision="0" />
            </a-form-model-item>
          </template>
          <template #constituteStatusSlot="text, record">
            <a-tag v-if="record.constituteStatus == 1" color="#108ee9"> 单品 </a-tag>
            <a-tag v-else color="#87d068"> 组合 </a-tag>
          </template>
          <span slot="action" slot-scope="text, record, index">
            <a @click="delProduct(index)">删除</a>
          </span>
        </a-table>
      </a-form-model>
    </a-spin>
    <template #footer>
      <a-button @click="modalVisible = false"> 取消 </a-button>
      <a-button type="primary" :loading="submitLoading" @click="submit"> 保存 </a-button>
    </template>
    <!-- 产品选择弹窗 -->
    <product-check-modal
      v-if="showProductCheck"
      :visible.sync="showProductCheck"
      :defaultData="formData.hzArchiveShopSkuItemsList"
      @submit="submitProductCheck"
    />
  </j-modal>
</template>

<script>
import { getAction, postAction } from '@/api/manage'

import ProductCheckModal from '@/components/business/ProductCheckModal.vue'

export default {
  name: 'ArchiveShopSkuMapingModal',
  components: { ProductCheckModal },
  props: {
    // 要编辑的产品档案id，为空表示新增
    editId: {
      type: String,
      default: '',
    },
    // 是否显示弹框
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      showProductCheck: false, // 是否显示产品选择弹框
      modalVisible: this.visible,
      submitLoading: false,
      selectedRowKeys: [], // 选中的行的key
      formData: {
        platformSkuCode: '',
        shopId: '',
        hzArchiveShopSkuItemsList: [],
      },
      rules: {
        platformSkuCode: [{ required: true, message: '请输入平台sku!' }],
        shopId: [{ required: true, message: '请输入所属店铺!' }],
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      url: {
        add: '/hzkj-product/product/archive/hzArchiveShopSkuMaping/add',
        edit: '/hzkj-product/product/archive/hzArchiveShopSkuMaping/edit',
        queryById: '/hzkj-product/product/archive/hzArchiveShopSkuMaping/queryById',
        queryListById: '/hzkj-product/product/archive/hzArchiveShopSkuMaping/queryHzArchiveShopSkuItemsByMainId',
        validateSkuCode: '/hzkj-product/product/archive/hzArchiveShopSkuMaping/matchCode',
      },
      formColumns: [
        {
          title: '序号',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '图片',
          align: 'center',
          scopedSlots: { customRender: 'imgSlot' },
        },
        {
          title: '仓库SKU',
          align: 'center',
          dataIndex: 'skuCode',
        },
        {
          title: '产品名称',
          align: 'left',
          dataIndex: 'name',
        },
        {
          title: '颜色/尺寸',
          align: 'left',
          dataIndex: 'colorSize',
        },
        {
          align: 'center',
          slots: { title: 'numTitle' },
          scopedSlots: { customRender: 'numSlot' },
        },
        {
          title: '组合状态',
          align: 'center',
          scopedSlots: { customRender: 'constituteStatusSlot' },
        },
        {
          title: '操作',
          align: 'center',
          width: 150,
          scopedSlots: { customRender: 'action' },
        },
      ],
    }
  },
  watch: {
    modalVisible(val) {
      this.$emit('update:visible', val)
    },
  },
  methods: {
    getInfo() {
      return new Promise((resolve) => {
        getAction(this.url.queryById, { id: this.editId }).then((res) => {
          if (res.success) {
            resolve(res.result)
          } else {
            this.$message.warning(res.message)
          }
        })
      })
    },
    getList() {
      return new Promise((resolve) => {
        getAction(this.url.queryListById, { id: this.editId }).then((res) => {
          if (res.success) {
            resolve(res.result)
          } else {
            this.$message.warning(res.message)
          }
        })
      })
    },
    submitProductCheck(arr) {
      const parseArr = arr.map((item) => {
        let imgUrl = ''
        if (item.imgUrl) {
          imgUrl = item.imgUrl
        } else if (item.hzArchiveInfoImgsList) {
          imgUrl = item.hzArchiveInfoImgsList.find((i2) => i2.izMaster == 1).url
        }
        return {
          archiveBasicId: item.archiveBasicId || item.id,
          colorSize: item.colorSize || item.hzArchiveInfoOtherList[0].color + ';' + item.hzArchiveInfoOtherList[0].size, // 颜色/尺寸等信息
          constituteStatus: item.constituteStatus,
          count: 1, // 默认数量为1
          imgUrl,
          name: item.name || item.nameCn,
          skuCode: item.skuCode,
        }
      })
      this.formData.hzArchiveShopSkuItemsList = JSON.parse(JSON.stringify(parseArr))
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    //删除产品
    delProduct(index) {
      this.selectedRowKeys = []
      if (index != undefined) {
        this.formData.hzArchiveShopSkuItemsList.splice(index, 1)
      } else {
        // 批量删除
        this.formData.hzArchiveShopSkuItemsList = this.formData.hzArchiveShopSkuItemsList.filter(
          (item) => !this.selectedRowKeys.includes(item.skuCode)
        )
      }
    },
    submit() {
      this.$refs.form.validate((pass) => {
        if (!pass) {
          return
        }
        if (this.formData.hzArchiveShopSkuItemsList.length == 0) {
          this.$message.error('请至少添加一个产品')
          return
        }
        this.submitLoading = true
        if (this.editId == this.formData.id) {
          // 如果是编辑且ID没有变更，直接提交
          this.sendForm()
          return
        }
        // 否则查询平台SKU映射关系是否存在
        getAction(this.url.validateSkuCode, {
          platformSkuCode: this.formData.platformSkuCode,
        })
          .then((res) => {
            if (!res.result) {
              this.sendForm()
              return res.result
            }
            this.$confirm({
              content: (h) => {
                return h(
                  'div',
                  {
                    domProps: {
                      innerHTML: `<div style="padding-left: 40px;"><span style="font-weight: bold;">平台SKU映射关系在系统中已存在</span>，<span style="color: red">继续会覆盖原映射关系</span>，你还要继续吗？</div>`,
                    },
                  },
                  []
                )
              },
              onOk: () => {
                this.sendForm()
              },
            })
          })
          .finally(() => {
            this.submitLoading = false
          })
      })
    },
    sendForm() {
      this.submitLoading = true
      postAction(this.editId ? this.url.edit : this.url.add, this.formData)
        .then((res) => {
          if (res.success) {
            this.$message.success(`${this.editId ? '编辑' : '新增'}成功`)
            this.modalVisible = false // 关闭弹框
            this.$emit('submit', res.result) // 通知父组件提交成功
          } else {
            this.$message.error(res.message)
          }
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
  },
  created() {
    if (this.editId) {
      // 编辑，需要回显
      this.submitLoading = true
      Promise.all([this.getInfo(), this.getList()]).then(([resInfo, resList]) => {
        this.formData = {
          id: resInfo.id,
          platformSkuCode: resInfo.platformSkuCode,
          shopId: resInfo.shopId,
          hzArchiveShopSkuItemsList: resList.map((i) => ({
            archiveBasicId: i.archiveBasicId,
            imgUrl: i.imgUrl,
            skuCode: i.skuCode,
            name: i.name,
            colorSize: i.colorSize,
            count: i.count,
            constituteStatus: i.constituteStatus,
          })),
        }
        this.submitLoading = false
      })
    }
  },
}
</script>

<style lang="less" scoped>
.img-box {
  width: 60px;
  height: 60px;
  margin-right: 10px;
  display: inline-block;
  cursor: pointer;
  position: relative;
  background-color: #fafafa;
  img {
    width: 100%;
    height: 100%;
  }
  .hint-text {
    width: 100%;
    height: 20px;
    line-height: 20px;
    font-size: 11px;
    text-align: center;
    position: absolute;
    left: 0;
    bottom: 0;
    color: #fff;
    background-color: rgba(0, 0, 0, 0.5);
  }
}
.required-ico {
  margin-right: 4px;
  color: #f5222d;
  font-size: 14px;
}
</style>
